package com.p2l.letterblocks;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Bundle;

public class ActivityLevel extends Activity {
	private ActivityLevel context;
	
	private SQLiteDatabase sqlite;
	private Database db;
	
	private SharedPreferences preferences;
	private LinearLayout level_layout, background;
	private TextView bar;
	
	private ArrayList<Level> levels;
	
	private int[] completed;
	private float text, size, padding;
	private int userId, chapterId, language;
	
	private OnClickListener listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			int levelId = (Integer) v.getTag();
			DialogDifficulty d = new DialogDifficulty(context, levelId, userId);
			d.show();
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.level);
		
		bar = (TextView) findViewById(R.id.lblChooseLevel);
		level_layout = (LinearLayout) findViewById(R.id.level_layout);
		background = (LinearLayout) findViewById(R.id.level_background);
		background.setBackgroundResource(R.drawable.level_selection_background);

		context = this;
		preferences = getSharedPreferences("LetterBlocks", MODE_PRIVATE);
		
		completed = new int[] { R.drawable.levels_completed_1_coin, R.drawable.levels_completed_2_coin, R.drawable.levels_completed_3_coin };
		
		userId = getIntent().getIntExtra("userId", -1);
		chapterId = getIntent().getIntExtra("chapterId", -1);
		language = preferences.getInt("language", -1);
		text = getResources().getDimension(R.dimen.level);
		size = getResources().getDimension(R.dimen.letterblocks_level);
		padding = getResources().getDimension(R.dimen.padding_small);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		db = new Database(context);
		sqlite = db.getWritableDatabase();
		
		// get all levels in the chapter on the device
		String select = "SELECT *";
		String where = " WHERE chapterId='" + chapterId + "'";
		Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_LEVELS, "", where);
		levels = db.getLevels(cursor);
		
		ArrayList<LevelCompleted> levels_completed = new ArrayList<LevelCompleted>();
		if (levels.size() > 0) {
			String ids = "";
			for (Level l : levels)
				ids += (ids.length() == 0 ? "levelId='" : " OR levelId='") + l.getId() + "'" + (userId == -1 ? "" : " AND userId='" + userId + "'") + " AND language='" + language + "'";
			
			where = " WHERE " + ids;
			cursor = db.select(sqlite, select, Database.TABLE_NAME_LEVELS_COMPLETED, "", where);
			levels_completed.addAll(db.getLevelsCompleted(cursor));
			ids = null;
		}
		
		for (LevelCompleted l : levels_completed) {
			boolean found = false;
			int i = 0;
			
			while (!found && i < levels.size()) {
				if (levels.get(i).getId() == l.getLevelId())
					found = true;
				else
					i++;
			}
			levels.get(i).setCompleted(found);
		}
		
		level_layout.removeAllViews();
		
		int rows = (levels.size() / 4) + (levels.size() % 4 == 0 ? 0 : 1);
		for (int i = 0; i < rows; i++) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			params.gravity = Gravity.CENTER;
			
			LinearLayout.LayoutParams text_params = new LinearLayout.LayoutParams((int)size, (int)size);
			
			LinearLayout l = new LinearLayout(this);
			l.setLayoutParams(params);
			
			for (int j = 0; j < 4; j++) {
				int level = (i * 4) + j + 1;

				TextView t = new TextView(this);
				
				if (level <= levels.size()) {
					t.setTag(levels.get(level - 1).getId());
					t.setText("" + level);
					t.setTextSize(text);
					t.setTextColor(0x7f000000);
					t.setGravity(Gravity.CENTER_HORIZONTAL);
					t.setLayoutParams(text_params);
					t.setPadding(0, (int)padding, 0, 0);
					
					if (levels.get(level - 1).isCompleted()) {
						int coins = 0;
						
						select = "SELECT *";
						where = " WHERE levelId='" + levels.get(level - 1).getId() + "' AND coin='1'" + (userId == -1 ? "" : " AND userId='" + userId + "'") + " AND language='" + language + "'";
						cursor = db.select(sqlite, select, Database.TABLE_NAME_LEVELS_COMPLETED, "", where);
						if (cursor.getCount() > 0) {
							coins++;
						} else {
							select = "SELECT *";
							where = " WHERE levelId='" + levels.get(level - 1).getId() + "' AND type='1'";
							cursor = db.select(sqlite, select, Database.TABLE_NAME_OBJECTS, "", where);
							if (cursor.getCount() == 0)
								coins++;
						}
						
						select = "SELECT *";
						where = " WHERE levelId='" + levels.get(level - 1).getId() + "'" + (userId == -1 ? "" : " AND userId='" + userId + "'") + " AND language='" + language + "'";
						cursor = db.select(sqlite, select, Database.TABLE_NAME_LEVELS_COMPLETED, "", where);
						if (cursor.getCount() > 1)
							coins++;
						
						t.setBackgroundDrawable(getResources().getDrawable(completed[coins]));
						t.setOnClickListener(listener);
					} else {
						if (level - 1 == 0) {
							t.setBackgroundDrawable(getResources().getDrawable(R.drawable.levels_completed_0_coin));
							t.setOnClickListener(listener);
						} else if (levels.get(level - 2).isCompleted()) {
							t.setBackgroundDrawable(getResources().getDrawable(R.drawable.levels_completed_0_coin));
							t.setOnClickListener(listener);
						} else {
							t.setText("");
							t.setBackgroundDrawable(getResources().getDrawable(R.drawable.levels_locked));
						}
					}
				}
				
				l.addView(t);
			}
			level_layout.addView(l);
		}
		db.close();
		db = null;
		sqlite = null;
		select = null;
		where = null;
		cursor = null;
		levels_completed.clear();
		levels_completed = null;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (background.getBackground() != null)
			background.getBackground().setCallback(null);
		if (bar.getBackground() != null)
			bar.getBackground().setCallback(null);
		
		for (int i = 0; i < level_layout.getChildCount(); i++) {
			LinearLayout l = (LinearLayout) level_layout.getChildAt(i);
			for (int j = 0; j < l.getChildCount(); j++) {
				TextView t = (TextView) l.getChildAt(j);
				if (t.getBackground() != null)
					t.getBackground().setCallback(null);
			}
			l.removeAllViews();
		}
		level_layout.removeAllViews();
		levels.clear();

		level_layout = null;
		preferences = null;
		background = null;
		completed = null;
		listener = null;
		levels = null;
		bar = null;
		
		System.gc();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK) {
			boolean daily = data.getBooleanExtra("daily", false);
			boolean sound = data.getBooleanExtra("sound", false);
			if (daily) {
				DialogDailyCoin d = new DialogDailyCoin(this);
				d.show();
			} else if (sound) {
				DialogSound d = new DialogSound(this);
				d.show();
			} else {
				boolean rated = preferences.getBoolean("rated", false);
				if (!rated) {
					db = new Database(context);
					sqlite = db.getWritableDatabase();
					
					String select = "SELECT COUNT(*)";
					String where = " WHERE userId='" + userId + "'";
					Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_LEVELS_COMPLETED, "", where);
					if (cursor.moveToFirst()) {
						int completed = cursor.getInt(0);
						if (completed % 5 == 0) {
							DialogRate d = new DialogRate(context);
							d.show();
						}
					}
					db.close();
				}
			}
		}
	}
}